<?php
/**
 * Zeed Platform Project
 * Based on Zeed Framework & Zend Framework.
 *
 * LICENSE
 * http://www.zeed.com.cn/license/
 *
 * @category Zeed
 * @package Zeed_ChangeMe
 * @subpackage ChangeMe
 * @copyright Copyright (c) 2010 Zeed Technologies PRC Inc. (http://www.zeed.com.cn)
 * @author Zeed Team (http://blog.zeed.com.cn)
 * @since 2010-12-6
 * @version SVN: $Id$
 */

class ShareController extends ArchiveAdminAbstract
{
    protected $perpage = 20;
    
    /**
     * 分享列表
     */
    public function index()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $ordername = $this->input->get('ordername', null);
        $orderby = $this->input->get('orderby', null);
        $page = (int) $this->input->get('pageIndex', 0);
        $perpage = (int) $this->input->get('pageSize', $this->perpage);
        $key = trim($this->input->get('key'));
        $time_start = $this->input->get('time_start');
        $time_end = $this->input->get('time_end');
        $temp_userid = (int) $this->input->get('temp_userid');
        
        /* ajax 加载数据 */
        if ($this->input->isAJAX()) {
            $offset = $page * $perpage;
            $page = $page + 1;
            
            /* 组织查询条件 */
            $where = array(
                    'userid' => $this->_userid,
                    'status' => 1
            );
            if ($time_start && $time_end) {
                /* 处理时间排序 */
                $time_se = array($time_start, $time_end);
                asort($time_se);
                $time_se = array_values($time_se);
                $time_start = $time_se[0];
                $time_end = $time_se[1];

                $where['$and'] = [
                        ['ctime'=>
                                ['$gte' => strtotime($time_start) * 1000] // new MongoDate()
                        ],
                        ['ctime'=>
                                ['$lte' =>  (strtotime($time_end) + 24 * 3600 - 1) * 1000]
                        ]
                ];
            } else {
                if ($time_start) {
                    $startime = strtotime($time_start) * 1000; // new MongoDate(strtotime($time_start));
                    $where['ctime'] = ['$gte' => $startime];
                }
                
                if ($time_end) {
                    $endtime = (strtotime($time_end) + 24 * 3600 - 1) * 1000;
                    $where['ctime'] = ['$lte' => $endtime];
                }
            }
            if ($temp_userid) {
                $where['share_to'] = $temp_userid;
            }
            if ($key) {
                $where['$or'] = array(
                        array('sn' => new MongoRegex("/$key/i"))
                );
            }
            $order = array('ctime' => 'DESC');
            
            /* 执行查询 */
            $content = Archive_Model_Share::instance()->fetchByWhere($where, $order, $perpage, $offset);
            $data['count'] = Archive_Model_Share::instance()->getCount($where);

            /* 处理其他一些信息 */
            if (! empty($content)) {
                foreach ($content as $k => &$v) {
                    /* 处理案件名称 */
                    $content_info = Archive_Model_Content::instance()->fetchByFV('sn', $v['sn'], array('title'));
                    $v['title'] = $content_info[0]['title'];
                    
                    /* 处理被分享人 */
                    $share_to_info = Admin_Model_User::instance()->fetchByPK($v['share_to'], array('username', 'fullname'));
                    $v['share_to_name'] = $share_to_info[0]['fullname'] ? $share_to_info[0]['fullname'] : $share_to_info[0]['username'];
                    
                    /* 处理过期时间 */
                    if ($v['exptime']) {
                        if (strlen($v['exptime']) == 13) {
                            $v['exptime'] = date(DATETIME_FORMAT, $v['exptime'] / 1000);
                        } else {
                            $v['exptime'] = date(DATETIME_FORMAT, $v['exptime']);
                        }
                    } else {
                        $v['exptime'] = '永不过期';
                    }
                    
                    /* 处理分享时间 */
                    if (strlen($v['ctime']) == 13) {
                        $v['ctime'] = date(DATETIME_FORMAT, $v['ctime'] / 1000);
                    } else {
                        $v['ctime'] = date(DATETIME_FORMAT, $v['ctime']);
                    }
                }
            }
            
            $data['content'] = $content ? $content : array();
        }
        
        /* 获取临时用户信息 */
        $where_tempuser = 'status = 1 AND g.groupid = ' . $this->_user_group_temp;
        $order_tempuser = 'ctime DESC';
        $cols_tempuser = array('userid', 'username', 'fullname', 'ctime');
        $tempusers = Admin_Model_User::instance()->getUsersByGroupid($where_tempuser, $order_tempuser, null, null, $cols_tempuser);
        
        $data['tempusers'] = $tempusers;
        
        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'share.index');
        return parent::multipleResult(self::RS_SUCCESS);
    }
    
    /**
     * 编辑
     */
    public function edit ()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        if ($this->input->isPOST()) {
            $this->editSave();
            return self::RS_SUCCESS;
        }
        
        /* 接收参数 */
        $_id = $this->input->query('_id');
        
        /* 检查内容是否存在 */
        $content = Archive_Model_Content::instance()->fetchByPK($_id);
        if (empty($content)) {
            throw new Zeed_Exception('查无此案件。');
        }
        $content = $content[0];
        
        /* 获取已分享人员信息 */
        $where_share = array('sn' => $content['sn'], 'status' => 1);
        $share_info = Archive_Model_Share::instance()->fetchByWhere($where_share);
        
        /* 处理已分享用户 ID 及用户名等信息 */
        $post_temp_userid = array();
        if (! empty($share_info)) {
            foreach ($share_info as $k => &$v) {
                $post_temp_userid[] = $v['share_to'];
                
                $user_info = Admin_Model_User::instance()->fetchByPK($v['share_to'], array('fullname'));
                if (! empty($user_info)) {
                    $v['fullname'] = $user_info[0]['fullname'];
                }
                
                $v['exptime'] = Util_Timer::formatMicrotime($v['exptime'], 'Y-m-d H:i:s');
            }
        }
        
        $data = array(
                '_id' => $_id,
                'content' => $content,
                'share_info' => $share_info,
                'post_temp_userid' => ! empty($post_temp_userid) ? implode(',', $post_temp_userid) : '',
        );
        
        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'share.edit');
        return parent::multipleResult(self::RS_SUCCESS);
    }
    
    /**
     * 编辑 - 保存
     */
    public function editSave ()
    {
        $set = $this->_validate();
        if ($set['status'] == 0) {
            try {
                $timenow = Util_Timer::getMicrotime();
                
                /* 查询案件是否已存在 */
                $content_info = Archive_Model_Content::instance()->fetchByPK($set['data']['_id']);
                if (empty($content_info)) {
                    throw new Zeed_Exception('查无此案件');
                }
                $content_info = $content_info[0];
                
                /* 处理过期时间 */
                $exptime = strtotime($set['data']['exptime']) * 1000;
                
                /* 处理用户 ID */
                $temp_userids_arr = explode(',', $set['data']['post_temp_userid']);
                
                /* 删除原有绑定关系 */
                Archive_Model_Share::instance()->deleteByFV('sn', $content_info['sn']);
                
                /* 循环处理绑定关系 */
                if (! empty($temp_userids_arr)) {
                    foreach ($temp_userids_arr as $k => $v) {
                        /* 添加绑定关系 */
                        $set_add = array(
                                'sn' => $content_info['sn'],
                                'title' => $content_info['title'],
                                'category_name' => $content_info['category_name'],
                                'department_name' => $content_info['department_name'],
                                'description' => $content_info['description'],
                                'label' => $content_info['label'],
                                'tte' => $content_info['tte'],
                                'share_to' => (int) $v,
                                'exptime' => (int) $exptime,
                                'userid' => $this->_userid,
                                'status' => 1,
                                'ctime' => $timenow,
                                'mtime' => $timenow
                        );
                        Archive_Model_Share::instance()->addForEntity($set_add);
                    }
                }
                
                /* @todo 记录日志 */
                
            } catch (Zeed_Exception $e) {
                $this->setStatus(1);
                $this->setError('分享失败 : ' . $e->getMessage());
                return false;
            }
            return true;
        }
        $this->setStatus($set['status']);
        $this->setError($set['error']);
        return false;
    }
    
    /**
     * 保存 － 校验
     */
    private function _validate ()
    {
        $res = array('status' => 0, 'error' => null, 'data' => null);
        
        try {
            $res['data'] = array(
                    '_id' => $this->input->post('_id', ''),
                    'exptime' => $this->input->post('exptime'),
                    'post_temp_userid' => $this->input->post('post_temp_userid')
            );
            
            /* 数据验证 - 基础信息 */
            if (! $res['data']['post_temp_userid']) {
                throw new Zeed_Exception('请填至少选择一个用户');
            }
        } catch (Zeed_Exception $e) {
            $res['status'] = 1;
            $res['error'] = $e->getMessage();
        }
        
        return $res;
    }
    
    /**
     * 获取临时用户列表
     */
    public function getTempuser()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        try {
            /* 接收参数 */
            $ordername = $this->input->get('ordername', null);
            $orderby = $this->input->get('orderby', null);
            $page = (int) $this->input->get('pageIndex', 0);
            $perpage = (int) $this->input->get('pageSize', $this->perpage);
            $key = trim($this->input->get('key'));
            
            /* 组织翻页条件 */
            $offset = $page * $perpage;
            $page = $page + 1;
            
            /* 组织查询条件 */
            $where = 'status = 1 AND g.groupid = ' . $this->_user_group_temp;
            if ($key) {
                $where .= ' AND (u.username LIKE "%' . $key . '%" OR u.fullname LIKE "%' . $key . '%")';
            }
            $order = 'ctime DESC';
            $cols = array('userid', 'username', 'fullname', 'ctime');
            
            /* 执行查询 */
            $content = Admin_Model_User::instance()->getUsersByGroupid($where, $order, $perpage, $offset, $cols);
            $data['count'] = Admin_Model_User::instance()->getUsersCountByGroupid($where);
            
            $data['content'] = ! empty($content) ? $content : array();
            
            $this->setData('data', $data);
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('查询失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 更新分享信息
     */
    public function updateExptime()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        try {
            /* 接收参数 */
            $_id = $this->input->post('_id');
            $exptime = $this->input->post('exptime');
            
            /* 查询分享信息是否存在 */
            $share_info = Archive_Model_Share::instance()->fetchByPK($_id);
            if (empty($share_info)) {
                throw new Zeed_Exception('查无此分享信息');
            }
            
            /* 判断权限 */
            if ($share_info[0]['userid'] != $this->_userid) {
                throw new Zeed_Exception('不可编辑他人的分享信息');
            }
            
            /* 执行更新 */
            $set_update = array(
                    'exptime' => strtotime($exptime) * 1000,
                    'mtime' => Util_Timer::getMicrotime()
            );
            Archive_Model_Share::instance()->updateForEntity($set_update, $_id);
            
            /* @todo 记录日志 */
            
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('更新失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 取消分享
     */
    public function cancel()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        try {
            /* 接收参数 */
            $_id = $this->input->post('_id');
            
            /* 查询分享信息是否存在 */
            $share_info = Archive_Model_Share::instance()->fetchByPK($_id);
            if (empty($share_info)) {
                throw new Zeed_Exception('查无此分享信息');
            }
            
            /* 判断权限 */
            if ($share_info[0]['userid'] != $this->_userid) {
                throw new Zeed_Exception('不可操作他人的分享信息');
            }
            
            /* 执行取消 */
            Archive_Model_Share::instance()->deleteByPK($_id);
            
            /* @todo 记录日志 */
            
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('取消失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
}

// End ^ LF ^ encoding
